<template>
  <div>
    <div style="text-align: left; margin-bottom: 5px">
      <el-button size="mini" type="primary" @click="toAddUser">
        添加
      </el-button>
    </div>

    <!--增加或更新管理员的表单弹窗-->
    <el-dialog :title=formTitle :visible.sync="flagShowForm">
      <el-form ref="userForm" :model="formData" label-width="100px">
        <el-form-item label="店铺id" required>
          <el-select v-model="formData.shopId" placeholder="请选择店铺id" style="float: left">
            <el-option v-for="(item,index) in shopList" :key="index" :label="'[店铺id' + item.id + '] ' + item.name"
                       :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户名" required>
          <el-input v-model="formData.username" placeholder="请输入管理员名" maxlength="20"></el-input>
        </el-form-item>
        <el-form-item label="手机" required>
          <el-input v-model="formData.phone" placeholder="请输入手机号" maxlength="11"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetForm">重置</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!--选择角色弹窗-->
    <el-dialog title="设置角色" :visible.sync="flagShowSetRole">
      <div>
        <el-button size="mini" :class="{selected: formData.roleIdList && formData.roleIdList.indexOf(role.id)>=0}"
                   v-for="(role,index) in roleList" :key="index"
                   @click="setUserRole(role.id)">
          {{ role.name }}
        </el-button>
      </div>
      <el-button type="primary" size="mini" @click="confirmSetRole" style="margin-top: 10px">确定更新</el-button>
    </el-dialog>

    <!--列表-->
    <el-table
        :data="userList.slice((searchParams.pageNo-1)*searchParams.pageSize, searchParams.pageNo * searchParams.pageSize)"
        :default-sort="{prop: 'id'}">
      <el-table-column label="id" prop="id" sortable></el-table-column>
      <el-table-column label="店铺id" prop="shopId"></el-table-column>
      <el-table-column label="用户名" prop="username" sortable></el-table-column>
      <el-table-column label="手机" prop="phone" sortable></el-table-column>
      <el-table-column label="角色" prop="roleNames"></el-table-column>
      <el-table-column label="头像" prop="wxAvatar">
        <template slot-scope="scope">
          <img :src="scope.row.avatar" alt="" style="width: 50px; height: 50px; border-radius: 50%;">
        </template>
      </el-table-column>
      <el-table-column label="账号状态">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status===1" @change="changeSysUserStatus(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="170px">
        <template slot-scope="scope">
          <el-button @click="goSetRole(scope.row)" type="text">设置角色</el-button>
          <el-button @click="toEditUser(scope.row)" type="text">编辑</el-button>
          <el-button @click="deleteSysUser(scope.row)" type="text">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--分页组件-->
    <el-row style="float: right">
      <el-pagination
          @current-change="changePageNo"
          @size-change="changePageSize"
          :current-page.sync="searchParams.pageNo"
          :page-size.sync="searchParams.pageSize"
          :page-sizes="[5, 10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </el-row>

  </div>
</template>

<script>
import * as roleAdminApi from "../../api/system/roleAdminApi";
import * as shopAdminApi from "../../api/system/shopAdminApi";
import * as sysUserAdminApi from "../../api/system/sysUserAdminApi";

export default {
  data() {
    return {
      shopList: [], // 店铺列表
      // 查询参数
      searchParams: {
        pageNo: 1,
        pageSize: 10,
      },
      total: 0,
      userList: [],
      flagShowForm: false,
      formTitle: '增加',
      formData: {},
      roleList: [],
      flagShowSetRole: false, // 角色授权对话框
      curRoleId: null
    }
  },
  mounted() {
    this.getSysUserList();
    // 获取店铺列表
    shopAdminApi.getShopList({
      success: res => {
        this.shopList = res.data
      }
    })
    // 获取角色列表
    roleAdminApi.getRoleList({
      success: res => {
        this.roleList = res.data
      }
    })
  },
  methods: {
    // 获取管理员列表
    getSysUserList() {
      sysUserAdminApi.getSysUserList({
        success: res => {
          this.userList = res.data
          this.total = this.userList.length
        }
      })
    },
    // 切换页数
    changePageNo(pageNo) {
      this.searchParams.pageNo = pageNo;
      this.getUserList()
    },
    // 改变页面大小
    changePageSize(pageSize) {
      this.searchParams.pageSize = pageSize;
      this.getUserList()
    },
    // 重置表单
    resetForm() {
      this.formData = {
        phone: "",
        username: '',
        password: "",
        roleIdList: [],
      }
    },
    toAddUser() {
      this.resetForm()
      this.flagShowForm = true
      this.formTitle = '添加管理员'
    },
    deleteSysUser(user) {
      this.$confirm(`是否删除管理员: ${user.username}`).then(() => {
        sysUserAdminApi.deleteSysUser({
          sysUserId: user.id,
          success: () => {
            this.getSysUserList()
          }
        })
      }).catch(() => {
      })
    },
    // 编辑管理员
    toEditUser(sysUser) {
      this.formData = JSON.parse(JSON.stringify(sysUser));
      this.flagShowForm = true
      this.formTitle = '更新管理员'
    },
    // 提交表单
    submitForm() {
      this.formData.username = this.formData.username.trim()
      let err = ""
      if (this.formData.username === "")
        err = "请输入用户名"
      else if (!/^1\d{10}$/.test(this.formData.phone))
        err = "手机号格式错误"
      if (err !== "") {
        this.$message.error(err)
        return
      }

      if (this.formTitle.startsWith('添加')) {
        sysUserAdminApi.addSysUser({
          data: this.formData,
          success: res => {
            this.flagShowForm = false
            this.$msgbox.alert("添加成功，该管理员的初始密码为：" + res.data)
            this.getSysUserList()
          }
        })
      } else if (this.formTitle.startsWith('更新')) {
        sysUserAdminApi.updateSysUser({
          data: this.formData,
          success: () => {
            this.flagShowForm = false
            this.getSysUserList()
          }
        })
      }
    },
    // 改变账号状态
    changeSysUserStatus(user) {
      let newStatus = (user.status === 1 ? 2 : 1)
      sysUserAdminApi.updateSysUser({
        data: {
          ...user,
          status: newStatus,
        },
        success: () => {
          this.$notify.success(newStatus === 1 ? "已激活" : "已冻结")
          user.status = newStatus
        }
      })
    },
    // 去设置角色列表
    goSetRole(user) {
      this.flagShowSetRole = true
      this.formData = JSON.parse(JSON.stringify(user))
    },
    setUserRole(roleId) {
      console.info("setUserRole: ", roleId)
      let index = this.formData.roleIdList.findIndex(id => {
        return id === roleId
      })
      if (index < 0)
        this.formData.roleIdList.push(roleId)
      else {
        this.formData.roleIdList.splice(index, 1)
      }
    },
    // 设置管理员的角色列表
    confirmSetRole() {
      console.log(this.formData.roleIdList)
      sysUserAdminApi.updateSysUser({
        data: this.formData,
        success: () => {
          this.flagShowSetRole = false
          this.getSysUserList()
        }
      })
    }
  }
}
</script>
<style>
.selected {
  color: green !important;
}
</style>
